<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="80%">
    <el-descriptions
      :column="3"
      border
      v-loading="formLoading"
    >
      <el-descriptions-item label-width="125" min-width="140"  label="档案编码">{{ formData.recordCode }}</el-descriptions-item>
      <el-descriptions-item label-width="125" label="企业名称">{{ formData.companyName }}</el-descriptions-item>
      <el-descriptions-item label-width="125" label="统一社会信用代码">{{ formData.unifiedSocialCreditCode }}</el-descriptions-item>
      <el-descriptions-item label="所属经济城">{{ formData.economicZone }}</el-descriptions-item>
      <el-descriptions-item label="纳税人属性">
        <dict-tag :type="DICT_TYPE.OA_TAXPAYER_ATTRIBUTE" :value="formData.taxpayerType" />
      </el-descriptions-item>
       <el-descriptions-item label="登记机关">{{ formData.registrationAuthority }}</el-descriptions-item>
       <el-descriptions-item label="公司类型">{{ formData.companyType }}</el-descriptions-item>
      <el-descriptions-item label="主管税务机关">{{ formData.taxOffice }}</el-descriptions-item>

      <el-descriptions-item label="税务管理员">{{ formData.taxSupervisor }}</el-descriptions-item>


      <el-descriptions-item label="注册资金">{{ formData.registeredCapital }} 万</el-descriptions-item>

      <el-descriptions-item label="注册地址">{{ formData.registeredAddress }}</el-descriptions-item>

      <el-descriptions-item label="成立日期">{{ formatDate2(formData.establishmentDate) }}</el-descriptions-item>
      <el-descriptions-item label="经营期限">{{ formData.operationPeriod }}</el-descriptions-item>

      <el-descriptions-item label="开户银行">{{ formData.bankName }}</el-descriptions-item>
      <el-descriptions-item label="开户账号">{{ formData.bankAccount }}</el-descriptions-item>
      <el-descriptions-item label="法定代表人">{{ formData.legalPersonName }}</el-descriptions-item>
      <el-descriptions-item label="法人身份证号">{{ formData.legalPersonId }}</el-descriptions-item>
      <el-descriptions-item label="法人电话号码">{{ formData.legalPersonPhone }}</el-descriptions-item>

      <el-descriptions-item label="企业联系人">{{ formData.companyContact }}</el-descriptions-item>
      <el-descriptions-item label="企业联系电话">{{ formData.contactPhone }}</el-descriptions-item>
      <el-descriptions-item label="介绍人">{{ formData.referrer }}</el-descriptions-item>
      <el-descriptions-item label="委托开始时间">
        <div v-if="formData.entrustStartYear>0">{{ formData.entrustStartYear + '-' + formData.entrustStartMonth }}</div>
      </el-descriptions-item>
      <el-descriptions-item label="委托结束时间">
        <div v-if="formData.entrustEndYear>0">{{ formData.entrustEndYear + '-' + formData.entrustEndMonth }}</div>
      </el-descriptions-item>

      <el-descriptions-item label="企业邮箱">{{ formData.companyEmail }}</el-descriptions-item>
      <el-descriptions-item label="招商负责人">{{ formData.investmentManager }}</el-descriptions-item>

      <el-descriptions-item label="财务记账负责人">{{ formData.accountingManager }}</el-descriptions-item>
       <el-descriptions-item label="企业信用等级">{{ formData.creditRating }}</el-descriptions-item>

      <el-descriptions-item label="是否简化企业">
        <el-tag v-if="formData.simplified === 1" type="success">是</el-tag>
        <el-tag v-else type="info">否</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="是否重点企业">
        <el-tag v-if="formData.keyEnterprise === 1" type="success">是</el-tag>
        <el-tag v-else type="info">否</el-tag>
      </el-descriptions-item>
      <!-- <el-descriptions-item label="网厅财务负责人">{{ formData.onlineFinanceManager }}</el-descriptions-item> -->
      <el-descriptions-item label="委托内容">{{ formData.entrustContent }}</el-descriptions-item>

      <el-descriptions-item label="收费价格(月)">{{ formData.monthlyFee }} 元</el-descriptions-item>
      <el-descriptions-item label="收款公司">{{ formData.paymentCompany }}</el-descriptions-item>
      <el-descriptions-item label="记账费开票">
        <el-tag v-if="formData.includeAccounting === 1" type="success">是</el-tag>
        <el-tag v-else type="info">否</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="开票备注">{{ formData.invoiceRemark }}</el-descriptions-item>

      <!-- <el-descriptions-item label="企业信用等级">{{ formData.creditRating }}</el-descriptions-item> -->
\
      <!-- <el-descriptions-item label="创建者">{{ formData.creatorName }}</el-descriptions-item> -->
      <el-descriptions-item label="" />
      <el-descriptions-item label="" />
      <el-descriptions-item label="经营范围" :span="3">{{ formData.businessScope }}</el-descriptions-item>
      <el-descriptions-item label="备注" :span="3">{{ formData.remarks }}</el-descriptions-item>


    </el-descriptions>

    <!-- Tab标签页 -->
    <el-tabs v-model="activeTab" type="border-card" class="mt-10px" v-if="formData.id > 0">
      <!-- 股东信息 Tab -->
      <el-tab-pane label="股东信息" name="shareholder">
        <div class="mb-10px">
          <el-button
            type="primary"
            @click="openShareholderForm"
          >
            <Icon icon="ep:plus" /> 新增股东
          </el-button>
        </div>
        <shareholder-list 
          ref="shareholderListRef" 
          :company-id="formData.id" 
          :business-type="'accounting-companies'" 
          type="list" 
          :key="`shareholder-${formData.id}`"
        />
      </el-tab-pane>
      
      <!-- 收费价格 Tab -->
      <el-tab-pane label="收费价格" name="price">
        <price-adjustment-list 
          :company-id="formData.id" 
          :key="`price-${formData.id}`"
        />
      </el-tab-pane>
      
      <!-- 开票信息 Tab -->
      <el-tab-pane label="开票信息" name="invoice">
        <invoice-form 
          :company-id="formData.id" 
          :key="`invoice-${formData.id}`"
        />
      </el-tab-pane>
      
      <!-- 收款信息 Tab -->
      <el-tab-pane label="收款信息" name="payment">
        <payment-form 
          :company-id="formData.id" 
          :key="`payment-${formData.id}`"
        />
      </el-tab-pane>
    </el-tabs>

    <!-- 股东表单弹窗 -->
    <company-shareholders-form ref="shareholderFormRef" type="form" />

    <template #footer>
      <el-button @click="dialogVisible = false">关 闭</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { DICT_TYPE } from '@/utils/dict'
import { formatDate,formatDate2 } from '@/utils/formatTime'
import { AccountingCompaniesApi, AccountingCompaniesVO } from '@/api/oa/accountingcompanies'
import ShareholderList from './components/ShareholderList.vue'
import CompanyShareholdersForm from '../companyshareholders/CompanyShareholdersForm.vue'
import PriceAdjustmentList from './components/PriceAdjustmentList.vue'
import InvoiceForm from './components/InvoiceForm.vue'
import PaymentForm from './components/PaymentForm.vue'

/** 记账企业详情 表单 */
defineOptions({ name: 'AccountingCompaniesDetail' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中
const activeTab = ref('shareholder') // 当前激活的Tab
const formData = ref<AccountingCompaniesVO>({
  id: 0,
  recordCode: '',
  economicZone: '',
  taxOffice: '',
  registeredCapital: 0,
  operationPeriod: '',
  bankAccount: '',
  legalPersonName: '',
  legalPersonPhone: '',
  companyContact: '',
  contactPhone: '',
  investmentManager: '',
  referrer: '',
  companyName: '',
  taxpayerType: '',
  taxSupervisor: '',
  registeredAddress: '',
  companyEmail: '',
  supervisor: '',
  entrustStartDate: '',
  accountingManager: '',
  unifiedSocialCreditCode: '',
  registrationAuthority: '',
  companyType: '',
  establishmentDate: new Date(),
  bankName: '',
  legalPersonId: '',
  entrustEndDate: '',
  onlineFinanceManager: '',
  businessScope: '',
  remarks: '',
  entrustContent: '',
  simplified: 0,
  keyEnterprise: 0,
  monthlyFee: 0,
  includeAccounting: 0,
  invoiceRemark: '',
  paymentCompany: '',
  creditRating: '',
  creatorName: '',
  updaterName: '',
  entrustStartYear: 0,
  entrustStartMonth: 0,
  entrustEndYear: 0,
  entrustEndMonth: 0,
})

const shareholderListRef = ref() // 股东列表组件引用
const shareholderFormRef = ref() // 新增股东表单组件引用

// 监听 formData.id 变化
watch(() => formData.value.id, (newId, oldId) => {
  console.log('AccountingCompaniesDetail - formData.id changed:', { oldId, newId })
}, { immediate: true })

/** 打开股东表单 */
const openShareholderForm = () => {
  shareholderListRef.value?.openForm('create', undefined, {
    companyName: formData.value.companyName,
    businessType: 'accounting-companies'
  })
}

/** 打开弹窗 */
const open = async (id: number) => {
  dialogVisible.value = true
  dialogTitle.value = '查看记账企业详情'
  formLoading.value = true
  try {
    // 先重置 formData，确保子组件能感知到变化
    formData.value = {
      id: 0,
      recordCode: '',
      economicZone: '',
      taxOffice: '',
      registeredCapital: 0,
      operationPeriod: '',
      bankAccount: '',
      legalPersonName: '',
      legalPersonPhone: '',
      companyContact: '',
      contactPhone: '',
      investmentManager: '',
      referrer: '',
      companyName: '',
      taxpayerType: '',
      taxSupervisor: '',
      registeredAddress: '',
      companyEmail: '',
      supervisor: '',
      entrustStartDate: '',
      accountingManager: '',
      unifiedSocialCreditCode: '',
      registrationAuthority: '',
      companyType: '',
      establishmentDate: new Date(),
      bankName: '',
      legalPersonId: '',
      entrustEndDate: '',
      onlineFinanceManager: '',
      businessScope: '',
      remarks: '',
      entrustContent: '',
      simplified: 0,
      keyEnterprise: 0,
      monthlyFee: 0,
      includeAccounting: 0,
      invoiceRemark: '',
      paymentCompany: '',
      creditRating: '',
      creatorName: '',
      updaterName: '',
      entrustStartYear: 0,
      entrustStartMonth: 0,
      entrustEndYear: 0,
      entrustEndMonth: 0,
    }
    
    // 等待下一个 tick，确保重置生效
    await nextTick()
    
    // 然后加载新数据
    formData.value = await AccountingCompaniesApi.getAccountingCompanies(id)
  } finally {
    formLoading.value = false
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
</script>
